<template>
  <div class="pluto-table-print">
    <el-card>
      <div slot="header" v-if="title.length>0" class="card-header">
        <span>{{ title }}</span>
      </div>

      <!-- 筛选区域 - 升级版 -->
      <div class="filter-section" v-if="hasSearchFields || showAddButton">
        <el-form :model="searchParams" ref="searchForm" :inline="true" class="search-form">


          <!-- 循环生成搜索字段 -->
          <el-form-item
            v-for="column in searchColumns"
            :key="column.prop"
            :label="column.label"
            :prop="column.prop"
          >
            <!-- 输入框 -->
            <el-input
              v-if="column.type === 'input' || !column.type"
              v-model="searchParams[column.prop]"
              :placeholder="`请输入${column.label}`"
              clearable
              @keyup.enter.native="handleSearch"
              style="width: 180px"
            ></el-input>

            <!-- 下拉选择框 -->
            <el-select
              v-else-if="column.type === 'select'"
              v-model="searchParams[column.prop]"
              :placeholder="`请选择${column.label}`"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="item in column.dataSource"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>

            <!-- 日期选择器 -->
            <el-date-picker
              v-else-if="column.type === 'date'"
              v-model="searchParams[column.prop]"
              type="date"
              :placeholder="`选择${column.label}`"
              value-format="yyyy-MM-dd"
              clearable
              style="width: 180px"
            ></el-date-picker>

            <!-- 日期区间选择器 -->
            <div v-else-if="column.type === 'date_interval'" class="date-interval-picker">
              <el-date-picker
                v-model="searchParams[getStartDateField(column.prop)]"
                type="date"
                :placeholder="`开始${column.label}`"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 150px; margin-right: 8px"
              ></el-date-picker>
              <span class="date-separator">至</span>
              <el-date-picker
                v-model="searchParams[getEndDateField(column.prop)]"
                type="date"
                :placeholder="`结束${column.label}`"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 150px"
              ></el-date-picker>
            </div>
          </el-form-item>
          <!-- 新增按钮 -->

          </el-form-item>
          <!-- 搜索按钮 -->
          <el-form-item class="search-buttons">
            <el-button v-if="showAddButton"
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >
              {{ addButtonText }}
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              :loading="filterLoading"
            >
              搜索
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-refresh"
              @click="handleResetFilter">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table
          ref="tableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
          stripe
          v-loading="loading"
        >
          <!-- 序号列 -->
          <el-table-column
            v-if="showIndex"
            type="index"
            label="序号"
            width="60"
            align="center"
          ></el-table-column>
          <!-- 多选框列 -->
          <el-table-column
            v-if="showSelection"
            type="selection"
            width="50"
            align="center"
          ></el-table-column>

          <!-- 循环生成所有列 -->
          <template v-for="column in columns">
            <!-- 自定义渲染列（使用插槽） -->
            <el-table-column
              v-if="column.slot"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              :sortable="column.sortable"
              :align="column.align || 'left'"
            >
              <template slot-scope="scope">
                <slot :name="column.slot" :row="scope.row" :index="scope.$index"></slot>
              </template>
            </el-table-column>

            <!-- 选择框数据格式化 -->
            <el-table-column
              v-else-if="isSelectColumn(column)"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              :sortable="column.sortable"
              :align="column.align || 'left'"
            >
              <template slot-scope="scope">
                {{ getSelectDisplayValue(column, scope.row[column.prop]) }}
              </template>
            </el-table-column>

            <!-- 自动渲染列（直接显示文本） -->
            <el-table-column
              v-else
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              :sortable="column.sortable"
              :align="column.align || 'left'"
            ></el-table-column>
          </template>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-section" v-if="showPagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'PlutoTablePrint',
  props: {
    title: {
      type: String,
      default: ''
    },
    columns: {
      type: Array,
      required: true,
      default: () => []
    },
    tableData: {
      type: Array,
      required: true,
      default: () => []
    },
    showSelection: {
      type: Boolean,
      default: true
    },
    showIndex: {
      type: Boolean,
      default: false
    },
    showPagination: {
      type: Boolean,
      default: true
    },
    pageSizes: {
      type: Array,
      default: () => [5, 10, 20, 50]
    },
    defaultPageSize: {
      type: Number,
      default: 5
    },
    total: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: false
    },
    // 新增按钮相关属性
    addButtonText: {
      type: String,
      default: ''  // 默认空字符串，不显示按钮
    }
  },
  data() {
    return {
      currentPage: 1,
      pageSize: this.defaultPageSize,
      selectedRows: [],
      filterLoading: false,
      searchParams: {}
    }
  },
  computed: {
    searchColumns() {
      if (!this.columns) return []
      return this.columns.filter(column => column.isSearch)
    },
    hasSearchFields() {
      return this.searchColumns.length > 0
    },
    // 是否显示新增按钮
    showAddButton() {
      return this.addButtonText && this.addButtonText.length > 0
    }
  },
  watch: {
    tableData: {
      handler() {
        this.selectedRows = [];
        if (this.$refs.tableRef) {
          this.$refs.tableRef.clearSelection();
        }
      },
      deep: true
    },
    defaultPageSize(newVal) {
      this.pageSize = newVal;
    }
  },
  methods: {
    // 初始化搜索参数
    initSearchParams() {
      this.searchParams = {}
      this.searchColumns.forEach(column => {
        if (column.type === 'date_interval') {
          this.$set(this.searchParams, this.getStartDateField(column.prop), '')
          this.$set(this.searchParams, this.getEndDateField(column.prop), '')
        } else {
          this.$set(this.searchParams, column.prop, '')
        }
      })
    },

    // 获取开始日期字段名
    getStartDateField(prop) {
      return `${prop}Start`
    },

    // 获取结束日期字段名
    getEndDateField(prop) {
      return `${prop}End`
    },

    // 判断是否为选择列
    isSelectColumn(column) {
      return column.type === 'select' && column.dataSource
    },

    // 获取选择框显示值
    getSelectDisplayValue(column, value) {
      if (!value) return ''
      const item = column.dataSource.find(item => item.key === value)
      return item ? item.value : value
    },

    // 构建完整的请求参数
    buildRequestParams() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      // 将搜索参数直接添加到根级别
      Object.keys(this.searchParams).forEach(key => {
        params[key] = this.searchParams[key]
      })
      return params
    },

    // 外部调用方法：获取选中数据
    getSelectedData() {
      return this.selectedRows;
    },

    // 新增按钮点击事件
    handleAdd() {
      this.$emit('add');
    },

    // 高级搜索处理
    handleSearch() {
      this.filterLoading = true;

      setTimeout(() => {
        this.currentPage = 1;
        this.filterLoading = false;

        // 构建请求参数 - 搜索参数直接与分页参数同级
        const requestParams = this.buildRequestParams()

        console.log('搜索参数:', requestParams)

        // 触发搜索事件，传递完整的请求参数
        this.$emit('search', requestParams);
      }, 300);
    },

    // 重置筛选
    handleResetFilter() {
      this.$refs.searchForm.resetFields();
      this.initSearchParams() // 重新初始化搜索参数
      this.currentPage = 1;

      // 构建重置后的请求参数
      const requestParams = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }

      this.$emit('reset', requestParams);
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.$emit('selection-change', selection);
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;

      // 构建分页参数 - 搜索参数直接与分页参数同级
      const requestParams = this.buildRequestParams()

      this.$emit('size-change', requestParams);
    },

    handleCurrentChange(val) {
      this.currentPage = val;

      // 构建分页参数 - 搜索参数直接与分页参数同级
      const requestParams = this.buildRequestParams()

      this.$emit('current-change', requestParams);
    },

    // 外部调用方法：设置高级搜索参数
    setSearchParams(params) {
      this.searchParams = {...this.searchParams, ...params}
    },

    // 外部调用方法：清空筛选
    clearFilter() {
      this.handleResetFilter();
    }
  },
  mounted() {
    this.pageSize = this.defaultPageSize;
    this.initSearchParams();
  }
}
</script>

<style scoped>
.pluto-table-print {
  margin: 20px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

/* 新增按钮样式 */
.add-button {
  //margin-right: 12px;
}

.search-buttons {
  //margin-left: auto;
}

.date-interval-picker {
  display: flex;
  align-items: center;
}

.date-separator {
  margin: 0 8px;
  color: #909399;
  font-size: 14px;
}

.table-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>
